package com.distributed.common.message;

import java.net.InetAddress;
import java.net.UnknownHostException;

import net.sf.json.JSONObject;

import com.distributed.common.Constant;
import com.distributed.util.Encryptor;

public class VerifyMessage extends BaseMessage {
	public VerifyMessage() {
		super();
		setId(Constant.VERIFY_MESSAGE);
	}

	public VerifyMessage(String username, String password) {
		super();
		setId(Constant.VERIFY_MESSAGE);
		setUserName(username);
		setPassword(password);
		setIp();
	}

	public static String getName() {
		return Constant.VERIFY_MESSAGE_NAME;
	}

	public void setUserName(String username) {
		argv.put(Constant.USER_NAME, username);
	}

	public String getUserName() {
		return argv.get(Constant.USER_NAME);
	}

	public void setPassword(String password) {
		argv.put(Constant.PASSWORD, Encryptor.MD5Encrytor(password));
	}

	public String getPassword() {
		return argv.get(Constant.PASSWORD);
	}

	public String getIp() {
		return argv.get(Constant.IP_S);
	}
	public void setIp() {
		try {
			InetAddress address = InetAddress.getLocalHost();
			argv.put(Constant.IP_S, address.getHostName());
		} catch(UnknownHostException e) {
			e.printStackTrace();
		}
	}
	
	public String getPort() {
		return argv.get(Constant.PORT_S);
	}
	public void setPort(int port) {
		argv.put(Constant.PORT_S, String.valueOf(port));
	}
	
	public static VerifyMessage getFromString(String message) {
		JSONObject jsonobject = JSONObject.fromObject(message);
		if (jsonobject == null) {
			return null;
		}
		return getFromJSON(jsonobject);
	}

	public static VerifyMessage getFromJSON(JSONObject jsonobj) {
		BaseMessage baseMessage = new VerifyMessage();
		BaseMessage baseMsg = BaseMessage.getFromJSON(jsonobj, baseMessage);
		if (baseMsg == null || baseMsg.getId() != Constant.LOGIN_MESSAGE) {
			return null;
		}
		String username = baseMsg.getArgvValue(Constant.USER_NAME);
		if (username == null || "".equals(username)) {
			return null;
		}
		String password = baseMsg.getArgvValue(Constant.PASSWORD);
		if (password == null || "".equals(password)) {
			return null;
		}
		
		return (VerifyMessage) baseMsg;
	}

	public JSONObject toJSON() {
		return super.toJSON();
	}
	
	public String toString() {
		return toJSON().toString();
	}
}
